package com.frame.platform.upload;

import java.io.*;
import java.util.*;

import com.frame.pageform.remote.RemoteCallFactory;
import com.frame.util.StreamUtils;

/**
 * 本地文件管理
 * @author Administrator
 *
 */
public class FileUpload {

	public static FileUpload getInstance() throws Exception{
		return (FileUpload)RemoteCallFactory.create(FileUpload.class,"fileServer");
	}
	/**
	 * 上传
	 *
	 * @param path
	 * @param body
	 * @throws IOException
	 */
	public void upload(String path,byte[] body) throws IOException{
		File newfile = new File(path);
		StreamUtils.byteToFile(body,newfile);
	}
	public void upload(String path,InputStream in) throws IOException{
		File newfile = new File(path);
		StreamUtils.streamToFile(in, newfile);
	}
	/**
	 * 获取文件列表
	 * @param dirPath
	 * @param ext
	 * @param sort
	 * @return
	 */
	public List getFileNameList(String dirPath, String[] ext, boolean sort) {
		List fileArr = new ArrayList();
		final String[] exts = ext;
		try {
			File file = new File(dirPath);
			if (!file.exists() || !file.isDirectory()) {
				file.mkdirs();
				file = new File(dirPath);
			}
			File[] files = file.listFiles(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					boolean bool = false;
					if(exts==null)
						bool= true;
					else{
						for (int i = 0; i < exts.length; i++) {
							if (name.toLowerCase().endsWith(exts[i])) {
								bool = true;
							}
						}
					}
					return bool;
				}
			});

			if (sort) {
				if (files != null && files.length > 0) {
					Arrays.sort(files, new Comparator() {
						public int compare(Object o1, Object o2) {
							long l = ((File) o1).lastModified() - ((File) o2).lastModified();
							if (l > 0)
								return -1;
							else if (l < 0)
								return 1;
							else
								return 0;
						}
					});
				}
			}

			for (int i = 0; i < files.length; i++) {
				fileArr.add(files[i].getName());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return fileArr;
	}
}
